import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


@WebServlet("/showRequest")
public class HttpServletRequestMethod extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);

        //使用 HttpServletRequest 的各种方法获取到 http请求的各种属性，在作为响应的body返回到页面中
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<h3>首行部分</h3>");
        stringBuilder.append(req.getProtocol());//协议名和版本
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());//请求 方法
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());//URL /helloservelet/showRequest
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());//   helloservelet
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());// 查询字符串内容
        stringBuilder.append("<br>");
        stringBuilder.append("<h3>header 部分</h3>");
        Enumeration<String> headerNames = req.getHeaderNames();//返回一个枚举，包含在该请求中包含的所有的头名
        while (headerNames.hasMoreElements()) {//遍历枚举里面的每一个元素
            String headerName = headerNames.nextElement(); //请求头的名字
            String headerValue = req.getHeader(headerName);//以字符串形式返回指定的请求头的值
            stringBuilder.append(headerName + ": " + headerValue + "<br>");
        }

        resp.setContentType("text/html; charset=utf8");
        resp.getWriter().write(stringBuilder.toString());
    }
}

